package org.lyq.erp.auth.menu.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.lyq.erp.auth.menu.mapper.MenuMapper;
import org.lyq.erp.auth.menu.pojo.Menu;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MenuServiceImpl implements MenuService {
	
	@Resource
	private MenuMapper menuMapper;

	public List<Menu> selectMenuByEmpUuid(Map<String, Integer> map) {
		return this.menuMapper.selectMenuByEmpUuid(map);
	}

	public List<Menu> selectAllMenu() {
		return this.menuMapper.selectAllMenu();
	}

	public List<Menu> selectAllMenuAndPmenu() {
		return this.menuMapper.selectAllMenuAndPmenu();
	}

	public List<Menu> selectAllPmenu() {
		return this.menuMapper.selectAllPmenu();
	}

	public Menu getMenuByMenuUuid(Integer menuUuid) {
		return this.menuMapper.getMenuByMenuUuid(menuUuid);
	}

	@Transactional
	public void update(Menu menu) {
		menu.setUpdatetime(Long.valueOf(System.currentTimeMillis()));

		this.menuMapper.updateByPrimaryKeySelective(menu);

		this.menuMapper.deleteAllRole(menu.getMenuUuid());

		Integer[] roleUuids = menu.getRoleUuids();
		Integer menuUuid = menu.getMenuUuid();
		insertMenuAndRole(roleUuids, menuUuid);
	}

	@Transactional
	public void insert(Menu menu) {
		menu.setCreatetime(Long.valueOf(System.currentTimeMillis()));
		menu.setUpdatetime(Long.valueOf(System.currentTimeMillis()));

		this.menuMapper.insertSelective(menu);

		Integer[] roleUuids = menu.getRoleUuids();
		Integer menuUuid = menu.getMenuUuid();
		insertMenuAndRole(roleUuids, menuUuid);
	}

	@Transactional
	public void delete(Integer menuUuid) {
		this.menuMapper.deleteMenuByMenuUuid(menuUuid);

		this.menuMapper.deleteAllRole(menuUuid);
	}

	private void insertMenuAndRole(Integer[] roleUuids, Integer menuUuid) {
		if (roleUuids != null) {

			List<Integer> list = new ArrayList<Integer>();
			Map<String, Object> map = new HashMap<String, Object>();

			for (int i = 0; i < roleUuids.length; i++) {
				list.add(roleUuids[i]);
			}
			map.put("menuUuid", menuUuid);
			map.put("list", list);
			this.menuMapper.insertMenuAndRole(map);

			list = null;
			map = null;
		}
	}
}
